using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Aurora.Redis.Consumers;

public class ListConsumer : BackgroundService
{
    private readonly IServiceProvider _serviceProvider;

    public ListConsumer(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Console.WriteLine("要开始消费了");
        await Task.Delay(5000);
        Console.WriteLine("真正开始消费了");
        // throw new NotImplementedException();
        var redis = ServiceProviderServiceExtensions.GetService<IRedisCache>(_serviceProvider.CreateScope().ServiceProvider);
        Console.WriteLine("[redis类型]" + redis.GetType().FullName);
        for (var index = 0; index < 5; index++)
        {
            await Task.Factory.StartNew(() => { Deal(stoppingToken); }, TaskCreationOptions.LongRunning);
        }

        async Task Deal(CancellationToken stoppingTokenItem)
        {
           
            while (!stoppingToken.IsCancellationRequested)
            {
                var threadId = Thread.CurrentThread.ManagedThreadId;
                try
                {
                    var queue = redis.LPop<string>("submit.test");
                    if (!string.IsNullOrEmpty(queue))
                    {
                        Console.WriteLine("[redis消息接收]  接收到了消息：" + queue+",ThreadId:"+threadId);
                    }
                    else
                    {
                        Console.WriteLine("[redis消息接收] 接收到的消息数量为空，开始休眠3秒," +
                                          DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+",ThreadId:"+threadId);
                        await Task.Delay(3000, stoppingToken);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    // _factory.Dispose();
                }

                //queue.Acknowledge()
            }
        }
    }
}